package com.stars.distributed.schedule.record;

import com.stars.distributed.schedule.bean.BatchResult;
import com.stars.distributed.schedule.bean.DbScheduleTask;
import com.stars.distributed.schedule.bean.DbScheduleTaskRecord;
import com.stars.distributed.schedule.service.DistributedScheduleService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 异步插入分布式调度主任务记录
 *
 * @author guoguifang
 */
public class AsynInsertTaskRecord extends BaseAsynchronousTask<List<Map<String, Object>>> {

    private static final AsynInsertTaskRecord ASYN_INSERT_TASK_RECORD = new AsynInsertTaskRecord();

    public static void add(List<Map<String, Object>> list) {
        ASYN_INSERT_TASK_RECORD.offer(list);
    }

    @Override
    protected BatchResult execute(List<List<Map<String, Object>>> list) throws Exception {
        List<DbScheduleTaskRecord> taskRecordList = new ArrayList<>();
        for (List<Map<String, Object>> subList : list) {
            for (Map<String, Object> map : subList) {
                DbScheduleTaskRecord dbScheduleTaskRecord = getDbScheduleTaskRecord(map);
                if (dbScheduleTaskRecord != null) {
                    taskRecordList.add(dbScheduleTaskRecord);
                }
            }
        }
        return DistributedScheduleService.getInstance().batchInsertDbScheduleTaskRecord(taskRecordList);
    }

    @Override
    protected long delayTime() {
        return 100;
    }

    private DbScheduleTaskRecord getDbScheduleTaskRecord(Map<String, Object> map) {
        DbScheduleTask dbScheduleTask = (DbScheduleTask) map.get("dto");
        String batchNo = dbScheduleTask.getBatchNo();
        if (batchNo != null) {
            DbScheduleTaskRecord dbScheduleTaskRecord = new DbScheduleTaskRecord();
            dbScheduleTaskRecord.setBatchNo(batchNo);
            dbScheduleTaskRecord.setPrevBatchNo((String) map.get("prevBatchNo"));
            dbScheduleTaskRecord.setTaskId(dbScheduleTask.getId());
            dbScheduleTaskRecord.setStatus(dbScheduleTask.getStatus());
            return dbScheduleTaskRecord;
        }
        return null;
    }

    private AsynInsertTaskRecord() {}

}
